package com.hopu.day6_springboot.controller;

import com.hopu.day6_springboot.entity.User;
import com.hopu.day6_springboot.service.UserService;
import com.hopu.day6_springboot.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 用户控制器
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(String username, String password,
                        String auto_login, String code,
                        HttpSession session, Model model,
                        HttpServletResponse resp){
        //把用户输入的验证码和session中验证码进行比较
        String code1 = (String) session.getAttribute("code");
        if(code1 == null || !code1.equals(code)){
            model.addAttribute("error","验证码错误");
            return "login";
        }
        try {
            User user = userService.login(username, password);
            if(user == null){
                //将错误信息保存到request对象
                model.addAttribute("error","账号或密码错误");
                return "login";
            }else{
                //判断是否免登录
                if("on".equals(auto_login)){
                    int time = 7 * 24 * 3600;
                    //保存账号密码到Cookie中
                    CookieUtil.save(resp,"username",username,time);
                    CookieUtil.save(resp,"password",password,time);
                }
                //将用户对象保存到session对象
                session.setAttribute("user",user);
                //如果登录成功，重定向到查询宠物的servlet
                return "redirect:findPetsPage";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "login";
        }
    }

    public static final String CHARS = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
    public static final int WIDTH = 100;
    public static final int HEIGHT = 40;
    public static final int FONT_SIZE = 25;

    @RequestMapping("/code.do")
    protected void createCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建内存图片
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        //获得图形对象
        Graphics graphics = bufferedImage.getGraphics();
        //设置颜色
        graphics.setColor(Color.GRAY);
        //设置字体
        graphics.setFont(new Font("宋体",Font.ITALIC,FONT_SIZE));
        //填充背景
        graphics.fillRect(0,0, WIDTH,HEIGHT);
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        //随机产生4个字符，绘制到图片上
        for(int i = 0;i < 4;i++){
            char c = CHARS.charAt(random.nextInt(CHARS.length()));
            code.append(c);
            //设置随机颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            graphics.setColor(color);
            //绘制字符
            graphics.drawString(String.valueOf(c),i * FONT_SIZE, FONT_SIZE);
        }
        //绘制干扰线条
        for (int i = 0; i < 8; i++) {
            //设置随机颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            graphics.setColor(color);
            graphics.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(WIDTH),random.nextInt(HEIGHT));
        }
        //保存验证码字符串到session中
        req.getSession().setAttribute("code",code.toString());
        //取消浏览器对图片的缓存
        resp.addHeader("Cache-Control","no-cache");
        //通过响应对象的输出流返回图片
        ImageIO.write(bufferedImage,"PNG",resp.getOutputStream());
    }
}
